import { javascriptGenerator } from 'blockly/javascript';

// 同步块的代码生成器
export const systemFunctionGenerators = {
  system_variable_get_history_value: function (block:any) {
    const variablePath =
      javascriptGenerator.valueToCode(block, 'VARIABLE_PATH', 0) || '""';

    const time =
      javascriptGenerator.valueToCode(block, 'TIME', 0) || 'new Date()';

    const code = `await System.Variable.getHistoryValue(${variablePath}, ${time})`;
    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 getHistoryValues 代码生成器
  system_variable_get_history_values: function (block:any) {
    const variablePath =
      javascriptGenerator.valueToCode(block, 'VARIABLE_PATH', 0) || '""';

    const startTime =
      javascriptGenerator.valueToCode(block, 'START_TIME', 0) ||
      'new Date(Date.now() - 3600000)'; // 默认一小时前

    const endTime =
      javascriptGenerator.valueToCode(block, 'END_TIME', 0) || 'new Date()'; // 默认当前时间

    const sampleType = block.getFieldValue('SAMPLE_TYPE');

    const samplePeriod =
      javascriptGenerator.valueToCode(block, 'SAMPLE_PERIOD', 0) || '60'; // 默认60秒

    // 构建代码，包含所有参数
    const code = `await System.Variable.getHistoryValues(${variablePath}, ${startTime}, ${endTime}, {type: "${sampleType}", period: ${samplePeriod}})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 getQuality 代码生成器
  system_variable_get_quality: function (block:any) {
    const variablePath =
      javascriptGenerator.valueToCode(block, 'VARIABLE_PATH', 0) || '""';

    // 构建代码
    const code = `await System.Variable.getQuality(${variablePath})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 getQualityInt 代码生成器
  system_variable_get_quality_int: function (block:any) {
    const variablePath =
      javascriptGenerator.valueToCode(block, 'VARIABLE_PATH', 0) || '""';

    // 构建代码
    const code = `await System.Variable.getQualityInt(${variablePath})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 getValue 代码生成器
  system_variable_get_value: function (block:any) {
    const variablePath =
      javascriptGenerator.valueToCode(block, 'VARIABLE_PATH', 0) || '""';

    const defaultValue =
      javascriptGenerator.valueToCode(block, 'DEFAULT_VALUE', 0) || 'null';

    // 构建代码
    const code = `await System.Variable.getValue(${variablePath}, ${defaultValue})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 isBadQuality 代码生成器
  system_variable_is_bad_quality: function (block:any) {
    const variablePath =
      javascriptGenerator.valueToCode(block, 'VARIABLE_PATH', 0) || '""';

    // 构建代码
    const code = `await System.Variable.isBadQuality(${variablePath})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 isGoodQuality 代码生成器
  system_variable_is_good_quality: function (block:any) {
    const variablePath =
      javascriptGenerator.valueToCode(block, 'VARIABLE_PATH', 0) || '""';

    // 构建代码
    const code = `await System.Variable.isGoodQuality(${variablePath})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 setValue 代码生成器
  system_variable_set_value: function (block:any) {
    const variablePath =
      javascriptGenerator.valueToCode(block, 'VARIABLE_PATH', 0) || '""';

    const value = javascriptGenerator.valueToCode(block, 'VALUE', 0) || 'null';

    const optionsType = block.getFieldValue('OPTIONS_TYPE');

    let code = '';

    // 根据选项类型生成不同的代码
    if (optionsType === 'NONE') {
      // 不设置时间和质量
      code = `await System.Variable.setValue(${variablePath}, ${value});\n`;
    } else {
      // 构建选项对象
      let options = '{';

      if (optionsType === 'BOTH' || optionsType === 'TIME_ONLY') {
        const time =
          javascriptGenerator.valueToCode(block, 'TIME', 0) || 'new Date()';
        options += `time: ${time}`;
      }

      if (optionsType === 'BOTH' || optionsType === 'QUALITY_ONLY') {
        if (options.length > 1) options += ', ';
        const quality =
          javascriptGenerator.valueToCode(block, 'QUALITY', 0) || '"Good"';
        options += `quality: ${quality}`;
      }

      options += '}';

      code = `await System.Variable.setValue(${variablePath}, ${value}, ${options});\n`;
    }

    return code;
  },

  // 新增的 System.ContextState.getValue 代码生成器
  system_context_state_get_value: function (block:any) {
    const stateId =
      javascriptGenerator.valueToCode(block, 'STATE_ID', 0) || '""';

    const defaultValue =
      javascriptGenerator.valueToCode(block, 'DEFAULT_VALUE', 0) || 'null';

    // 构建代码
    const code = `await System.ContextState.getValue(${stateId}, ${defaultValue})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 System.ContextState.setValue 代码生成器
  system_context_state_set_value: function (block:any) {
    const stateId =
      javascriptGenerator.valueToCode(block, 'STATE_ID', 0) || '""';

    const stateValue =
      javascriptGenerator.valueToCode(block, 'STATE_VALUE', 0) || 'null';

    // 构建代码
    const code = `await System.ContextState.setValue(${stateId}, ${stateValue});\n`;

    return code;
  },

  // 新增的 System.Logger.log 代码生成器
  system_logger_log: function (block:any) {
    const statusCode =
      javascriptGenerator.valueToCode(block, 'STATUS_CODE', 0) || '0';

    const message =
      javascriptGenerator.valueToCode(block, 'MESSAGE', 0) || '""';

    let code = '';

    // 检查是否有补充信息输入
    if (block.getInput('EXTRA_INFO')) {
      const extraInfo =
        javascriptGenerator.valueToCode(block, 'EXTRA_INFO', 0) || '[]';

      // 使用扩展运算符将数组展开为参数
      code = `await System.Logger.log(${statusCode}, ${message}, ...${extraInfo});\n`;
    } else {
      // 没有补充信息
      code = `await System.Logger.log(${statusCode}, ${message});\n`;
    }

    return code;
  },

  // 新增的 System.Mimic.back 代码生成器
  system_mimic_back: function (block:any) {
    // 构建代码
    const code = 'await System.Mimic.back();\n';

    return code;
  },

  // 新增的 System.Mimic.close 代码生成器
  system_mimic_close: function (block:any) {
    // 构建代码
    const code = 'await System.Mimic.close();\n';

    return code;
  },

  // 新增的 System.Mimic.open 代码生成器
  system_mimic_open: function (block:any) {
    const mimicPath =
      javascriptGenerator.valueToCode(block, 'MIMIC_PATH', 0) || '""';

    let code = '';

    // 检查是否有参数和变量目录替换输入
    const hasParams = block.getInput('MIMIC_PARAMS') !== null;
    const hasPathReplacement = block.getInput('PATH_REPLACEMENT') !== null;

    if (!hasParams && !hasPathReplacement) {
      // 只有画面路径
      code = `await System.Mimic.open(${mimicPath});\n`;
    } else if (hasParams && !hasPathReplacement) {
      // 有画面路径和参数
      const params =
        javascriptGenerator.valueToCode(block, 'MIMIC_PARAMS', 0) || 'null';
      code = `await System.Mimic.open(${mimicPath}, ${params});\n`;
    } else if (!hasParams && hasPathReplacement) {
      // 有画面路径和变量目录替换
      const pathReplacement =
        javascriptGenerator.valueToCode(block, 'PATH_REPLACEMENT', 0) || 'null';
      code = `await System.Mimic.open(${mimicPath}, null, ${pathReplacement});\n`;
    } else {
      // 有画面路径、参数和变量目录替换
      const params =
        javascriptGenerator.valueToCode(block, 'MIMIC_PARAMS', 0) || 'null';
      const pathReplacement =
        javascriptGenerator.valueToCode(block, 'PATH_REPLACEMENT', 0) || 'null';
      code = `await System.Mimic.open(${mimicPath}, ${params}, ${pathReplacement});\n`;
    }

    return code;
  },

  // 新增的 System.Mimic.openNewTab 代码生成器
  system_mimic_open_new_tab: function (block:any) {
    const mimicPath =
      javascriptGenerator.valueToCode(block, 'MIMIC_PATH', 0) || '""';

    let code = '';

    // 检查是否有参数和变量目录替换输入
    const hasParams = block.getInput('MIMIC_PARAMS') !== null;
    const hasPathReplacement = block.getInput('PATH_REPLACEMENT') !== null;

    if (!hasParams && !hasPathReplacement) {
      // 只有画面路径
      code = `await System.Mimic.openNewTab(${mimicPath});\n`;
    } else if (hasParams && !hasPathReplacement) {
      // 有画面路径和参数
      const params =
        javascriptGenerator.valueToCode(block, 'MIMIC_PARAMS', 0) || 'null';
      code = `await System.Mimic.openNewTab(${mimicPath}, ${params});\n`;
    } else if (!hasParams && hasPathReplacement) {
      // 有画面路径和变量目录替换
      const pathReplacement =
        javascriptGenerator.valueToCode(block, 'PATH_REPLACEMENT', 0) || 'null';
      code = `await System.Mimic.openNewTab(${mimicPath}, null, ${pathReplacement});\n`;
    } else {
      // 有画面路径、参数和变量目录替换
      const params =
        javascriptGenerator.valueToCode(block, 'MIMIC_PARAMS', 0) || 'null';
      const pathReplacement =
        javascriptGenerator.valueToCode(block, 'PATH_REPLACEMENT', 0) || 'null';
      code = `await System.Mimic.openNewTab(${mimicPath}, ${params}, ${pathReplacement});\n`;
    }

    return code;
  },

  // 新增的 System.Mimic.openOverlay 代码生成器
  system_mimic_open_overlay: function (block:any) {
    const mimicPath =
      javascriptGenerator.valueToCode(block, 'MIMIC_PATH', 0) || '""';

    const left = javascriptGenerator.valueToCode(block, 'LEFT', 0) || '0';

    const top = javascriptGenerator.valueToCode(block, 'TOP', 0) || '0';

    // 构建命令对象
    const command = `{ mimic: ${mimicPath}, left: ${left}, top: ${top} }`;

    let code = '';

    // 检查是否有参数和变量目录替换输入
    const hasParams = block.getInput('MIMIC_PARAMS') !== null;
    const hasPathReplacement = block.getInput('PATH_REPLACEMENT') !== null;

    if (!hasParams && !hasPathReplacement) {
      // 只有命令对象
      code = `await System.Mimic.openOverlay(${command});\n`;
    } else if (hasParams && !hasPathReplacement) {
      // 有命令对象和参数
      const params =
        javascriptGenerator.valueToCode(block, 'MIMIC_PARAMS', 0) || 'null';
      code = `await System.Mimic.openOverlay(${command}, ${params});\n`;
    } else if (!hasParams && hasPathReplacement) {
      // 有命令对象和变量目录替换
      const pathReplacement =
        javascriptGenerator.valueToCode(block, 'PATH_REPLACEMENT', 0) || 'null';
      code = `await System.Mimic.openOverlay(${command}, null, ${pathReplacement});\n`;
    } else {
      // 有命令对象、参数和变量目录替换
      const params =
        javascriptGenerator.valueToCode(block, 'MIMIC_PARAMS', 0) || 'null';
      const pathReplacement =
        javascriptGenerator.valueToCode(block, 'PATH_REPLACEMENT', 0) || 'null';
      code = `await System.Mimic.openOverlay(${command}, ${params}, ${pathReplacement});\n`;
    }

    return code;
  },

  // 新增的 System.Mimic.openPopup 代码生成器
  system_mimic_open_popup: function (block:any) {
    const mimicPath =
      javascriptGenerator.valueToCode(block, 'MIMIC_PATH', 0) || '""';

    const left = javascriptGenerator.valueToCode(block, 'LEFT', 0) || '0';

    const top = javascriptGenerator.valueToCode(block, 'TOP', 0) || '0';

    // 构建命令对象
    const command = `{ mimic: ${mimicPath}, left: ${left}, top: ${top} }`;

    let code = '';

    // 检查是否有参数和变量目录替换输入
    const hasParams = block.getInput('MIMIC_PARAMS') !== null;
    const hasPathReplacement = block.getInput('PATH_REPLACEMENT') !== null;

    if (!hasParams && !hasPathReplacement) {
      // 只有命令对象
      code = `await System.Mimic.openPopup(${command});\n`;
    } else if (hasParams && !hasPathReplacement) {
      // 有命令对象和参数
      const params =
        javascriptGenerator.valueToCode(block, 'MIMIC_PARAMS', 0) || 'null';
      code = `await System.Mimic.openPopup(${command}, ${params});\n`;
    } else if (!hasParams && hasPathReplacement) {
      // 有命令对象和变量目录替换
      const pathReplacement =
        javascriptGenerator.valueToCode(block, 'PATH_REPLACEMENT', 0) || 'null';
      code = `await System.Mimic.openPopup(${command}, null, ${pathReplacement});\n`;
    } else {
      // 有命令对象、参数和变量目录替换
      const params =
        javascriptGenerator.valueToCode(block, 'MIMIC_PARAMS', 0) || 'null';
      const pathReplacement =
        javascriptGenerator.valueToCode(block, 'PATH_REPLACEMENT', 0) || 'null';
      code = `await System.Mimic.openPopup(${command}, ${params}, ${pathReplacement});\n`;
    }

    return code;
  },

  // 新增的 System.Mimic.preload 代码生成器
  system_mimic_preload: function (block:any) {
    const mimicPath =
      javascriptGenerator.valueToCode(block, 'MIMIC_PATH', 0) || '""';

    // 检查是否有各种可选参数
    const hasParams = block.getInput('MIMIC_PARAMS') !== null;
    const hasPathReplacement = block.getInput('PATH_REPLACEMENT') !== null;
    const hasMaxCount = block.getInput('MAX_COUNT') !== null;

    // 准备参数
    let params = 'null';
    if (hasParams) {
      params =
        javascriptGenerator.valueToCode(block, 'MIMIC_PARAMS', 0) || 'null';
    }

    let pathReplacement = 'null';
    if (hasPathReplacement) {
      pathReplacement =
        javascriptGenerator.valueToCode(block, 'PATH_REPLACEMENT', 0) || 'null';
    }

    let maxCount = '';
    if (hasMaxCount) {
      maxCount =
        ', ' + (javascriptGenerator.valueToCode(block, 'MAX_COUNT', 0) || '1');
    }

    // 构建代码
    const code = `await System.Mimic.preload(${mimicPath}, ${params}, ${pathReplacement}${maxCount});\n`;

    return code;
  },

  // 新增的 System.Object.getChildNodePaths 代码生成器
  system_object_get_child_node_paths: function (block:any) {
    const parentPath =
      javascriptGenerator.valueToCode(block, 'PARENT_PATH', 0) || '""';

    // 构建代码
    const code = `await System.Object.getChildNodePaths(${parentPath})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 System.Object.getInnerFunctionMethods 代码生成器
  system_object_get_inner_function_methods: function (block:any) {
    const methodPaths =
      javascriptGenerator.valueToCode(block, 'METHOD_PATHS', 0) || '[]';

    // 构建代码
    const code = `await System.Object.getInnerFunctionMethods(${methodPaths})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 System.PageVariable.getValue 代码生成器
  system_page_variable_get_value: function (block:any) {
    const variablePath =
      javascriptGenerator.valueToCode(block, 'VARIABLE_PATH', 0) || '""';

    const defaultValue =
      javascriptGenerator.valueToCode(block, 'DEFAULT_VALUE', 0) || 'null';

    // 构建代码
    const code = `await System.PageVariable.getValue(${variablePath}, ${defaultValue})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 System.PageVariable.setValue 代码生成器
  system_page_variable_set_value: function (block:any) {
    const variablePath =
      javascriptGenerator.valueToCode(block, 'VARIABLE_PATH', 0) || '""';

    const value = javascriptGenerator.valueToCode(block, 'VALUE', 0) || 'null';

    // 构建代码
    const code = `await System.PageVariable.setValue(${variablePath}, ${value});\n`;

    return code;
  },

  // 新增的 System.Runtime.updateControl 代码生成器
  system_runtime_update_control: function (block:any) {
    const controlName =
      javascriptGenerator.valueToCode(block, 'CONTROL_NAME', 0) || '""';

    const controlProperties =
      javascriptGenerator.valueToCode(block, 'CONTROL_PROPERTIES', 0) || '{}';

    // 构建代码
    const code = `await System.Runtime.updateControl(${controlName}, ${controlProperties});\n`;

    return code;
  },

  // 新增的 System.SessionContext.getValue 代码生成器
  system_session_context_get_value: function (block:any) {
    const stateId =
      javascriptGenerator.valueToCode(block, 'STATE_ID', 0) || '""';

    const defaultValue =
      javascriptGenerator.valueToCode(block, 'DEFAULT_VALUE', 0) || 'null';

    // 构建代码
    const code = `await System.SessionContext.getValue(${stateId}, ${defaultValue})`;

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 System.SessionContext.setValue 代码生成器
  system_session_context_set_value: function (block:any) {
    const stateId =
      javascriptGenerator.valueToCode(block, 'STATE_ID', 0) || '""';

    const stateValue =
      javascriptGenerator.valueToCode(block, 'STATE_VALUE', 0) || 'null';

    // 构建代码
    const code = `await System.SessionContext.setValue(${stateId}, ${stateValue});\n`;

    return code;
  },

  // 新增的 System.Utils.getUserName 代码生成器
  system_utils_get_user_name: function (block: any) {
    // 构建代码
    const code = 'System.Utils.getUserName()';

    return [code, 0]; // 0 is ORDER_ATOMIC
  },

  // 新增的 System.Utils.redirect 代码生成器
  system_utils_redirect: function (block: any) {
    const url = javascriptGenerator.valueToCode(block, 'URL', 0) || '""';

    let code = '';

    // 检查是否有新窗口选项
    if (block.getField('NEW_TAB')) {
      const newTab = block.getFieldValue('NEW_TAB');
      code = `await System.Utils.redirect(${url}, ${newTab});\n`;
    } else {
      // 不指定新窗口选项，默认在新窗口打开
      code = `await System.Utils.redirect(${url});\n`;
    }

    return code;
  },

  // 新增的 System.Utils.scheduleTask 代码生成器
  system_utils_schedule_task: function (block: any) {
    // 获取函数参数，这里我们期望一个函数引用或者一个匿名函数
    const func =
      javascriptGenerator.valueToCode(block, 'FUNCTION', 0) || '() => {}';

    // 获取延迟毫秒数
    const milliseconds =
      javascriptGenerator.valueToCode(block, 'MILLISECONDS', 0) || '1000';

    // 构建代码
    const code = `System.Utils.scheduleTask(${func}, ${milliseconds});\n`;

    return code;
  },
};
